<?php
namespace app\index\controller;
use think\Request;
use think\Db;
use think\Cache;

class Pay extends \think\Controller
{
    public function pay2(){
        //沙盒账号khgxup5956@sandbox.com
        //沙盒密码111111
        header("Content-Type: text/html;charset=utf-8");
        $post_data = input('post.');
        require_once EXTEND_PATH.'alipay/wappay/service/AlipayTradeService.php';
        require_once EXTEND_PATH.'alipay/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';
        require EXTEND_PATH.'alipay/config.php';
        
        $good_id = input('get.good_id');
        $guigetype_id = input('guigetype_id'); 
        $ret = db('goods_attributes')->where("guigeType_id={$guigetype_id}")->find();
        $attributes_id = $ret['id'];

        $good_list = input('post.');
        $list = db('goods_attributes')->alias('a')->join('goods b','a.goods_id=b.id')->field('a.price,a.jifen,b.*')->where("goods_id={$good_id}")->find();
        
        $out_trade_no = date('YmdHis').mt_rand(1000 , 9999);
        if(isset($_GET['coupon_id'])){
            $coupon_id = input('get.coupon_id');
            $data = [
                'good_id' => $good_id,
                'address_id' => $good_list['address_id'],
                'subject' => $list['name'],
                'num' => $good_list['num'], 
                'total_amount' => $good_list['totalPrice'],
                'out_trade_no' => $out_trade_no,
                'attributes_id' => $attributes_id,
                'coupon_id' => $coupon_id,
            ];
        }else{
            $data = [
                'good_id' => $good_id,
                'address_id' => $good_list['address_id'],
                'subject' => $list['name'],
                'num' => $good_list['num'], 
                'total_amount' => $good_list['totalPrice'],
                'out_trade_no' => $out_trade_no,
                'attributes_id' => $attributes_id,
            ];
        }        
        session('dingdan_list',$data);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $data['out_trade_no'];
        // $out_trade_no = '70501111111S001111119';
    
        //订单名称，必填
        $subject = $data['subject'];
    
        //付款金额，必填
        $total_amount = $data['total_amount'];

        //商品描述，可空
        $body = '';
        //超时时间
        $timeout_express="1m";
    
        $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);
        
        $payResponse = new \AlipayTradeService($config);
        
        $result=$payResponse->wapPay($payRequestBuilder,$config['return_url'],$config['notify_url']);
    
        return $good_id;
    }
    public function paySuccess(){
        $dingdan_list = session('dingdan_list');
        // dump($dingdan_list);die;
        //判断结账来自"立即购买"还是"购物车"        
        if(count($dingdan_list) == count($dingdan_list, 1)){
            $data = [
                'user_id' => session('id'),     
                'address_id' => $dingdan_list['address_id'],
                'zhifu_id' => $dingdan_list['out_trade_no'],
                'total_money' => $dingdan_list['total_amount'],
                'dingdan_time' => date('Y-m-d H:i:s',time()),
            ];
            $ret = Db::name('dingdan')->insert($data);
            $dingdanId = Db::name('dingdan')->getLastInsID();
            $data2 = [
                'goods_id' => $dingdan_list['good_id'],
                'num' => $dingdan_list['num'],
                'dingdan_id' => $dingdanId,
                'attributes_id' => $dingdan_list['attributes_id'],
            ];
            db('dingdan_goods')->insert($data2);
            //减少库存
            Db::table('mall_goods_attributes')->where("id={$data2['attributes_id']}")->setDec('kucun',$data2['num']);
            //增加销量
            Db::table('mall_goods_attributes')->where("id={$data2['attributes_id']}")->setInc('sale',$data2['num']);            
            //删除用户已使用的优惠券
            if(isset($dingdan_list['coupon_id'])){
                db('coupon_user')->where("coupon_id={$dingdan_list['coupon_id']}")->delete();
            }
            $this->success('支付成功!','index/index');
        }else{
            $data = [
                'user_id' => session('id'),     
                'address_id' => $dingdan_list[0]['address_id'],
                'zhifu_id' => $dingdan_list[0]['out_trade_no'],
                'total_money' => $dingdan_list[0]['total_amount'],
                'dingdan_time' => date('Y-m-d H:i:s',time()),
            ];
            $ret = Db::name('dingdan')->insert($data);
            $dingdanId = Db::name('dingdan')->getLastInsID();
            foreach ($dingdan_list as $k => $v) {
                $data2 = [
                    'goods_id' => $v['good_id'],
                    'num' => $v['num'],
                    'dingdan_id' => $dingdanId,
                    'attributes_id' => $v['attributes_id'],
                ];
                $ret = db('dingdan_goods')->insert($data2);
                //减少库存
                Db::table('mall_goods_attributes')->where("id={$data2['attributes_id']}")->setDec('kucun',$data2['num']);
                //增加销量
                Db::table('mall_goods_attributes')->where("id={$data2['attributes_id']}")->setInc('sale',$data2['num']);
            }     
            if(isset($dingdan_list[0]['coupon_id'])){
                db('coupon_user')->where("coupon_id={$dingdan_list[0]['coupon_id']}")->delete();
            }   
            if($ret==false){
                $this->error('支付失败!');
            }else{
                session('dingdan_list',null);
                $this->success('支付成功!','index/index');
            }
        }        
    }
}
